import router from '@/route/index.js'
const toPage = (params) => {
  // 如果目标路由与当前路由一致，不执行跳转
  if (
    params === router.options.history.location ||
    params.path === router.options.history.location
  ) {
    return
  }
  typeof params === 'string' ? router.push(params) : router.push({ ...params })
}
const goPage = (num) => {
  // 如果目标路由与当前路由一致，不执行跳转
  router.go(num)
}

const directives = (app) => {
  //临时的图片加载失败处理
  app.directive('default-img', async function (el) {
    if (el.src) {
      let exist = await imageIsExist(el.src)
      if (!exist) {
        el.setAttribute(
          'src',
          new URL('../assets/img/nothing.png', import.meta.url)
        )
      } else {
        el.style.background = '#fff'
      }
    }
  })
}
let imageIsExist = function (url) {
  return new Promise((resolve) => {
    var img = new Image()
    img.src = url
    img.onload = function () {
      if (this.complete == true) {
        resolve(true)
        img = null
      }
    }
    img.onerror = function () {
      resolve(false)
      img = null
    }
  })
}

export default { toPage, goPage, directives }
